//
//  DetailViewController.swift
//  cysLibrarySys
//
//  Created by 曹亚索 on 2021/6/25.
//

import UIKit
import ZKProgressHUD
import LeanCloud

protocol ReSetDelegate {
    func reSet(ConnectedBook:Book)
}
protocol CancelSelectedDelegate {
    func cancelSelected()
}

class DetailViewController: UIViewController {

    private let spacing: CGFloat = 50
    var reSetDelegate : ReSetDelegate?
    var cancelSelectedDelegate : CancelSelectedDelegate?
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var bookFaceImageView: UIImageView!
    @IBOutlet weak var abstractLabel: UILabel!
    
    @IBOutlet weak var collectButton: UIButton!
    @IBAction func collect(_ sender: Any) {
        selectCollect()
    }
    @IBOutlet weak var borrowButton: UIButton!
    @IBAction func borrow(_ sender: Any) {
        selectBorrow()
    }
    
    //MARK:Life cycle
    override func viewWillAppear(_ animated: Bool) {
        commonInit()
        //页面复位
        UIView.animate(withDuration: 0.2) { [self] in
            scrollView.contentOffset = .zero
        }
    }
    
    override func viewDidLoad() {
        let gestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(dismissDetailViewController(pan:)))
        gestureRecognizer.edges = .left
        self.view.addGestureRecognizer(gestureRecognizer)
        
    }
    
    @objc func dismissDetailViewController(pan:UIScreenEdgePanGestureRecognizer){
        switch pan.state {
        case .began:
            self.dismiss(animated: true, completion: nil)
        default:
            break
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        cancelSelectedDelegate?.cancelSelected()
    }

    //MARK:Configuration
    private func commonInit(){
        setUpBookFaceImageView()
        setUpAbstractLabel()
        setUpBottomButton()
    }
    
    private func setUpBookFaceImageView(){
        //configuration
        if let currentBook = currentBook, let image = currentBook.face{
            bookFaceImageView.image = image
        }
    }
    
    private func setUpAbstractLabel(){
        abstractLabel.text = currentBook?.abstract
        //configuration
        abstractLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
        abstractLabel.sizeToFit()
    }
    

}

//MARK:BottomButton
extension DetailViewController{
    
    private func setUpBottomButton(){
        collectButton.layer.borderWidth = 2
        collectButton.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        collectButton.layer.cornerRadius = 10
        borrowButton.layer.borderWidth = 2
        borrowButton.layer.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        borrowButton.layer.cornerRadius = 10
        let isCollected = currentBook?.state.isCollected
        switch isCollected {
        case true:
            collectButton.isSelected = true
        case false:
            collectButton.isSelected = false
        default:
            break
        }
        let isBorrow = currentBook?.state.isBorrowed
        switch isBorrow {
        case true:
            borrowButton.isSelected = true
        case false:
            borrowButton.isSelected = false
        default:
            break
        }
    }
    private func selectCollect(){
        if userSelf != nil{
            if currentBook?.state.isCollected == false{
                userSelf?.collection += [currentBook!]
                let dateformatter = DateFormatter()
                dateformatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
                let time = dateformatter.string(from: Date())
                currentBook?.collectedTime = time
                currentBook?.state.isCollected = true
                LC.userHandleCollection(book: currentBook!, isCollect: true)
                collectButton.isSelected = !collectButton.isSelected
                ZKProgressHUD.showSuccess("收藏成功")
            }else{
                ZKProgressHUD.showInfo("您已收藏")
            }
        }else{
            ZKProgressHUD.showInfo("请先登录")
        }
    }
    private func selectBorrow(){
        if userSelf != nil{
            if currentBook?.state.isBorrowed == false{
                let alert = UIAlertController(title: "通过申请即可借阅", message: "是否提交申请", preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "提交", style: .default, handler: { [self] (send) in
                    userSelf?.borrow += [currentBook!]
                    currentBook?.state.isBorrowed = true
                    borrowButton.isSelected = !borrowButton.isSelected
                    LC.userHandleBorrow(book: currentBook!, isBorrow: true)
                    ZKProgressHUD.showSuccess("提交成功")
                }))
                alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
                present(alert, animated: true, completion: nil)
            }else{
                ZKProgressHUD.showInfo("您已借阅")
            }
        }else{
            ZKProgressHUD.showInfo("请先登录")
        }
    }
}
